package com.jia.blog.controller;



import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jia.blog.common.dto.LoginDto;
import com.jia.blog.common.lang.R;
import com.jia.blog.entity.User;
import com.jia.blog.service.UserService;
import com.jia.blog.util.JwtUtils;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@Api(tags = "登录退出管理")
@CrossOrigin
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/register")
    public R register(@Validated  @RequestBody LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        password = SecureUtil.md5(password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.save(user);
        return R.ok();
    }


    @PostMapping("/login")
    public R login(@Validated  @RequestBody LoginDto loginDto, HttpServletResponse response) {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user,"用户不存在");

        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return R.error().msg("密码错误");
        }

        String jwt = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization",jwt);
        response.setHeader("Access-control-Expose-Headers","Authorization");
        Map<Object, Object> map = MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("nickname", user.getNickname())
                .put("avatar", user.getAvatar())
                .put("phone", user.getPhone())
                .put("email", user.getEmail())
                .put("gender", user.getGender())
                .map();
        return R.ok().data("data",map);
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public R logout() {
        SecurityUtils.getSubject().logout();
        return R.ok();
    }
}
